package com.kcnet.qk.controller.addfriend;

import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.kcnet.qk.app.AppContext;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.constant.StringConst;
import com.kcnet.qk.controller.BasePeopleController;
import com.kcnet.qk.util.FBStringUtil;
import com.kcnet.qk.util.NodeUtil;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.RootShell;
import com.kcnet.qk.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jesse.nativelogger.NLogger;

import static com.kcnet.qk.constant.Const.LIST_VIEW;

/**
 * Created by Administrator on 2018/4/25 0025.
 * 根据名称搜索好友
 */

public class AddSearchPhoneCTR extends BasePeopleController {
    private boolean init_imm;

    private int inputNmaeCount = 0;
    private static String TAG = "根据名称搜索好友";

    private String city;
    private List<String> list = new ArrayList<>();

    private static AddSearchPhoneCTR mRongCloudInstance;

    private boolean isClickSeatch;
    private boolean isSearchHomeList; //是否进入了搜索主页列表
    private boolean isJoinHomeList; //是否进入了主页列表
    private boolean isClickAddFriend;
    private boolean isdoTaskStart;

    private boolean isClickCity;
    private boolean isJoinSeatchCity;
    private boolean isInputCity;
    protected Map<String, Boolean> mRecordMap = Collections.synchronizedMap(new HashMap());

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static AddSearchPhoneCTR getInstance() {
        if (mRongCloudInstance == null) {
            synchronized (AddSearchPhoneCTR.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new AddSearchPhoneCTR();
                }
            }
        }

        return mRongCloudInstance;
    }

    public void doTaslSearch() {

        if (!initFbMain && mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.FbUI.FBLauncherUI)) {
            NLogger.d(TAG, "1、点击搜索框");
            sleepTimedDefault();
            RootShell.click(81,38);
            isClickSeatch = true;
            initFbMain = true;
        } else if (isClickSeatch && mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals("com.facebook.katana.activity.ImmersiveActivity")) {
            NLogger.d(TAG, "2、事件 点击搜索框-输入主页名称");
            RootShell.click(182,75);
            sleepTimedDefault();
          //  Onclic_shell("81", "38");
            inputSayHiSentence(list.get(inputNmaeCount));

            NLogger.d(TAG, "3、输入完成事件");
            RootShell.keyevent(66);
            isSearchHomeList = true;
            isClickSeatch = false;

        } else if (isSearchHomeList && mType == AccessibilityEvent.TYPE_VIEW_SCROLLED && mClassName.equals("android.support.v7.widget.RecyclerView")) {
            NLogger.d(TAG, "4、搜索结果页");
            if (RootShell.click(90,110)) {
                isSearchHomeList = false;
                isJoinHomeList = true;//取消
            }
        } else if (isJoinHomeList && mType == AccessibilityEvent.TYPE_VIEW_SCROLLED && mClassName.equals("android.support.v7.widget.RecyclerView")) {
            NLogger.d(TAG, "5、事件 到达搜索主页");

            if (TextUtils.isEmpty(city)) {
                isJoinHomeList = false;
                isdoTaskStart = true;
            } else {
                NLogger.d(TAG, "5、输入筛选城市");
//                sleepTimedDefault();
                sleepTime(5000);
                //Onclic_shell("282", "110");
                RootShell.click(328,132);
                isJoinHomeList = false;
                isClickCity = true;

            }
        } else if (isdoTaskStart && (mType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && mClassName.equals("android.support.v7.widget.RecyclerView")
                || mType == AccessibilityEvent.TYPE_VIEW_SCROLLED && mClassName.equals("android.support.v7.widget.RecyclerView"))) {
            NLogger.d(TAG, "6 开始执行添加好友");
            beginReqAdd();
        } else if (isClickCity && mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals("X.3hz")) {
            NLogger.d(TAG, "7 点击删选输入框");
            sleepTimedDefault();
            Log.d(TAG, " getRoot().getChildCount()" + getRoot().getChildCount() + " s:" + getRoot().getChild(0).getChildCount());
            tagTextClickShell(getRoot().getChild(1).getChild(0));
            isClickCity = false;
            isJoinSeatchCity = true;
//            inputSayHiSentence(city);
        } else if (isJoinSeatchCity && mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals("X.3hz")) {
            NLogger.d(TAG, "8 进入城市搜索列表");
            inputSayHiSentence(city + "1");
            RootShell.keyevent(67);
           // execShellCmd("input keyevent  67");
            isInputCity = true;
            isJoinSeatchCity = false;
        } else if (isInputCity) {
            NLogger.d(TAG, "9 搜索完成");
            sleepTimedDefault();
            if (RootShell.click(0,212)) {
                isdoTaskStart = true;
                isInputCity = false;
            }
        }

    }

    @Override
    public void doTask(AccessibilityEvent event) {
        mClassName = (String) event.getClassName();

        mType = event.getEventType();
        doTaslSearch();

    }


    private void beginReqAdd() {
        AccessibilityNodeInfo scrllorNodeInfo = null;
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            synchronized (mLock) {
                List<AccessibilityNodeInfo> scrllorNodeInfos = NodeUtil.traverseNodeByClassList(root, "android.support.v7.widget.RecyclerView");
                if (scrllorNodeInfos.size() > 0) {
                    scrllorNodeInfo = scrllorNodeInfos.get(0);
                }
                if (scrllorNodeInfo == null) {
                    //  ToastUtil.showToast(AppContext.getInstance().getContext(),"scrllorNodeInfo listView null");
                    return;
                }
                for (int q = 0; q < scrllorNodeInfo.getChildCount(); q++) {

                    if (currentAddCount == maxAddCount) {
                        inputNmaeCount++;
                        if (inputNmaeCount == list.size()) {
                            inputNmaeCount = 0;
                            currentAddCount = 0;
                            mRecordMap.clear();
                            stopTask();
                            break;
                        } else {
                            currentAddCount = 0;
                            isdoTaskStart = false;
                            isClickSeatch = true;
                            tagTextClick(FBStringUtil.getString(StringConst.ADDFRIEND_SEARCH));
                        }
                        //停止任务
                        break;
                    }

                    AccessibilityNodeInfo nodeInfo = scrllorNodeInfo.getChild(q);
                    if (nodeInfo.getChildCount() > 0) {
                        try {
                            AccessibilityNodeInfo nameNode = nodeInfo.getChild(0).getChild(0);
                            if(nameNode.getContentDescription()==null){
                                nameNode = nodeInfo.getChild(0).getChild(0).getChild(0);
                            }
                            AccessibilityNodeInfo joinButtonNode = nameNode.getChild(0);
                            String name = nameNode.getContentDescription().toString();
                            if (!mRecordMap.containsKey(name)) {
                                if (joinButtonNode.getContentDescription().toString().equals(FBStringUtil.getString(StringConst.ADDFRIEND_JHYQQAN))) {
                                    NLogger.d(TAG, "点击 加好友请求按钮 "+name);
                                    isClickAddFriend = tagTextClickShell(joinButtonNode);
                                    if (isClickAddFriend) {
                                        mRecordMap.put(name, true);
                                        currentAddCount++;
                                        sleepTime(1000);//适当延迟，给系统反映时间
                                    }
                                }else {

                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                    Log.d(TAG, "q: "+q+" size:"+(scrllorNodeInfo.getChildCount() - 1));
                    if (q == scrllorNodeInfo.getChildCount() - 1) {
                        if (scrllorNodeInfo != null) {
                            //NodeUtil.performScroller(scrllorNodeInfo);
                          //  NodeUtil.performScroller(scrllorNodeInfo);
                            //execShellCmd("input swipe 0 800 0 600");
                            RootShell.swipe(0,800,0,500);
                            sleepTime(1000);//适当延迟，给系统反映时间
                            break;
                        }
                    }
                }
            }
        }
    }



    public void setParms(int maxAddCount, int minAddTime, int maxAddTime, String city, List<String> names) {
        //stopTask();
        EventBus.getDefault().post(new Boolean(true));
        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, true);
        this.maxAddCount = maxAddCount;
        this.minAddTime = minAddTime;
        this.maxAddTime = maxAddTime;
        this.currentAddCount = 0;
        this.list = names;
        this.city = city;
        this.init_imm = false;
        this.initFbMain = false;
        this.inputNmaeCount = 0;


        isClickSeatch = false;
        isSearchHomeList = false; //是否进入了搜索主页列表
        isJoinHomeList = false;//是否进入了主页列表
        isClickAddFriend = false;
        isdoTaskStart = false;

        isClickCity = false;
        isJoinSeatchCity = false;
        isInputCity = false;
    }


}
